package com.longtop.framework.security;

import com.longtop.framework.common.Message;

import java.util.ArrayList;
import java.util.List;

/**
 * 应用级异常（业务人员误操作产生的异常，如用户不存在、密码错误等等）的基类，是一个受控异常基类。
 * 
 * @author 胡砥峰
 */
public class BaseCheckedException extends Exception {

	private String exceptionKey = null; // 错误Key，用于唯一标识错误类型。 exceptionKey必须在common/applicationMessage.properties中定义。

	/**
	 * 传递给变量的错误值
	 */
	private Object[] exceptionValues = null;

	/**
	 * 根据Key从资源文件转成明文的错误信息
	 */
	private String message = null;

	public BaseCheckedException() {
		super();
	}

	public BaseCheckedException(String msg) {
		super();
		message = msg;
	}

	public BaseCheckedException(String key, String message) {
		super();
		this.exceptionKey = key;
		this.message = message;
	}

	public BaseCheckedException(String key, Object[] args) {
		super();
		this.exceptionKey = key;
		this.exceptionValues = args;
		// 转成明文错误信息
		this.message = Message.getMessage(key, args);
	}

	public BaseCheckedException(Throwable rootCause, String key, Object[] args) {
		super(rootCause);
		this.exceptionKey = key;
		this.exceptionValues = args;
		// 转成明文错误信息
		this.message = Message.getMessage(key, args);
	}

	public Object[] getExceptionValues() {
		return exceptionValues;
	}

	/**
	 * 获取异常Key
	 * 
	 * @return 异常Key
	 */
	public String getExceptionKey() {
		return exceptionKey;
	}

	/**
	 * 取得转成明文的错误信息
	 * 
	 * @return String 返回转成明文的错误信息
	 */
	public String getMessage() {
		return message == null || message.trim().equals("") ? super.getMessage() : message;
	}

	public String getMessagesString() {
		String[] msgs = this.getMessages();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < msgs.length; i++) {
			sb.append(msgs[i] + "\n");
		}
		return sb.toString();
	}

	public String[] getMessages() {
		Throwable[] throwables = this.getThrowables();
		String[] msgs = new String[throwables.length];
		for (int i = 0; i < throwables.length; i++) {
			msgs[i] = throwables[i].getMessage();
		}
		return msgs;
	}

	public Throwable[] getThrowables() {
		List list = new ArrayList();
		Throwable throwable = this;
		while (throwable != null) {
			list.add(throwable);
			throwable = throwable.getCause();
		}
		return (Throwable[]) list.toArray(new Throwable[list.size()]);
	}
}
